package edu.software.PBL_Management_System.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.software.PBL_Management_System.dto.ChatRequest;
import edu.software.PBL_Management_System.dto.DemandXmindDTO;
import edu.software.PBL_Management_System.service.ChildRequirmentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ChildRequirmentsImpl implements ChildRequirmentsService {


    @Value("${dify.api.base-url:http://localhost/v1}")
    private String difyBaseUrl;

    @Value("${dify.api.child.key}")
    private String difyChildKey;

    /**
     //     * WebClient 实例，用于发送HTTP请求
     //     */

    private final WebClient webClient;

    /**
     * JSON序列化/反序列化工具
     */
    private final ObjectMapper objectMapper;

    /**
     * 构造函数 - 初始化WebClient和ObjectMapper
     */
    public ChildRequirmentsImpl() {
        // 创建WebClient实例，配置超时时间
        this.webClient = WebClient.builder()
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(1024 * 1024)) // 设置最大内存缓冲区1MB
                .build();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 生成子需求
     * @param request
     * @return json格式数据
     */
    public String childRequirements(ChatRequest request) {
        log.info("开始调用Dify生成子需求");
        try {
            //准备发送给Dify的请求数据
            Map<String,Object> difyRequest = prepareDifyRequest(request);

            // 发送POST请求到Dify API
            String response = webClient.post()
                    .uri(difyBaseUrl + "/chat-messages")  // Dify聊天消息API端点
                    .header("Authorization", "Bearer " + difyChildKey)  // 设置认证头
                    .header("Content-Type", "application/json")       // 设置内容类型
                    .bodyValue(difyRequest)  // 设置请求体
                    .retrieve()  // 开始请求
                    .bodyToMono(String.class)  // 转换响应为String
                    .timeout(Duration.ofSeconds(60))  // 设置60秒超时
                    .block();  // 阻塞等待响应

            // 输出Dify返回的响应到控制台
            log.info("=== Dify API 响应成功 ===");


            return response;
        } catch (Exception e) {
            throw new RuntimeException("Dify 生成子需求失败", e);
        }
    }




    /**
     * 准备发送给Dify的请求数据
     * 将前端的ChatRequest转换为Dify API所需的格式
     *
     * @param request 前端聊天请求
     * @return Map<String, Object> Dify API请求格式
     */
    private Map<String,Object> prepareDifyRequest(ChatRequest request){
        //准备Dify请求数据
        Map<String,Object> difyRequest = new HashMap<>();

        // 设置必要的请求参数
        difyRequest.put("query", request.getQuery());  // 用户查询内容
        difyRequest.put("inputs", request.getInputs() != null ? request.getInputs() : new HashMap<>());  // 输入参数
        difyRequest.put("response_mode", request.getResponseMode());  // 响应模式
        difyRequest.put("user", request.getUser());  // 用户标识
        difyRequest.put("conversation_id", request.getConversationId());  // 会话ID

        // 如果有文件附件，添加到请求中
        if (request.getFiles() != null && !request.getFiles().isEmpty()) {
            difyRequest.put("files", request.getFiles());

        }
        // 是否自动生成会话名称
        difyRequest.put("auto_generate_name", request.getAutoGenerateName());
        return difyRequest;
    }
}
